#! /usr/bin/python3 python3
# -*- coding: utf-8 -*-

# *************************************************************
#  Projectname @  pysm
#     Filename @  redis.py
#       Author @  Steve.ma
#  Create date @  2018/8/31
#  Description @  
# *************************************************************

import redis
import json
from Conf import Conf,getConf

class SMCache :
    conf = None
    pool = False
    con = False

    def __init__(self):
        self.conf = getConf('redis')
        return
    #连接
    def conn(self):
        conf = self.conf
        if self.con != False :
            return
        else :
            if self.pool != False :
                self.con = redis.Redis(connection_pool=self.pool)
            else :
                self.pool = redis.ConnectionPool(host=conf['host'], port=conf['port'], db=conf['db'], password=conf['passwd'],decode_responses=True)
                self.con = redis.Redis(connection_pool=self.pool)
            return

    #设置缓存
    def setCache(self, name, value, ex=None):
        if self.con == False :
            self.conn()
        return self.con.set(name, json.dumps(value), ex)
    #获取缓存
    def getCache(self, name):
        if self.con == False :
            self.conn()
        keystatus = self.con.exists(name)
        if keystatus :
            return json.loads(self.con.get(name))
        else :
            return False
    #删除缓存
    def removeCache(self, name):
        if self.con == False :
            self.conn()
        keystatus = self.con.exists(name)
        if keystatus :
            return self.con.delete(name)
        else:
            return True
    #判断缓存是否存在
    def issetCache(self, name):
        if self.con == False :
            self.conn()
        return self.con.exists(name)

